<template>
  <view class="content">
    <view class="calendar-content">
      <view>
        <!-- 插入模式 -->
        <uni-calendar
          class="uni-calendar--hook"
          :selected="info.selected"
          :show-month="false"
          :lunar="true"
          @change="calendarChange"
          @monthSwitch="monthSwitch"
        />
      </view>
    </view>
    <view class="center-content">
      <u-checkbox
        v-model="checked"
        shape="circle"
        size="50"
        icon-size="30"
        class="group"
        style="padding:0rpx;border-top-width:0rpx"
        @change="checkedAll"
      >全选</u-checkbox>
      <span>今日任务</span>
      <u-button type="primary" size="medium" shape="square" @click="clockOrder">打卡</u-button>
    </view>
    <view class="plan-content">
      <u-checkbox-group class="group">
        <u-checkbox
          v-for="(item, index) in clockList"
          :key="index"
          v-model="item.checked"
          shape="circle"
          size="50"
          icon-size="30"
          :name="item.text"
          @change="checkboxChange"
        >{{ item.text }}</u-checkbox>
      </u-checkbox-group>
    </view>
    <!-- 组件 -->
    <u-modal
      v-model="deleteShow"
      :show-cancel-button="true"
      title="提示"
      :content="content"
      @confirm="handleClock"
    />
    <!-- 检测到新的版本 -->
    <u-modal
      v-model="show"
      :title="title"
      :show-cancel-button="false"
      @confirm="confirm"
    >
      <view style="margin: 50upx 60upx">
        检测到新的版本，更新内容如下：
        <view style="text-align: left;color:red">{{ msg }}</view>
        是否确认更新？
      </view>
    </u-modal>
    <!-- 升级新的版本 -->
    <u-popup
      v-model="showProgress"
      :mask-close-able="false"
      mode="center"
      width="80%"
      height="200rpx"
    >
      <view style="width: 80%; margin: 50rpx auto; text-align: center">
        <text>升级中...</text>
        <u-line-progress
          :percent="progress"
          :round="false"
          :striped="true"
          :striped-active="true"
        />
      </view>
    </u-popup>
    <view>
      <u-toast ref="uToast" />
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { formatDate, dateInterval } from '@/utils/utils'

export default {
  components: {},
  data() {
    return {
      checked: false,
      deleteShow: false,
      content: '',
      endDate: '',
      beginDate: '',
      fulldate: formatDate(),
      info: {
        lunar: true,
        range: true,
        insert: false,
        selected: []
      },
      clockList: [],
      holidayList: [],
      show: false,
      wgtUrl: '',
      msg: '',
      warningShow: false,
      showProgress: false,
      progress: 0,
      title: '*新版本升级',
      OrganizationsDefault: ''
    }
  },
  onLoad() {
    const [beginDate, endDate] = dateInterval()
    this.beginDate = beginDate
    this.endDate = endDate
    this.getClock()
  },
  onPullDownRefresh() {
    this.getClock('other')
    this.$u.toast('刷新成功!')
    uni.stopPullDownRefresh()
  },
  onLaunch: function() {
    // console.log('App Launch')
  },
  onShow() {
    const platform = uni.getSystemInfoSync().platform
    const that = this
    // #ifdef APP-PLUS
    plus.runtime.getProperty(plus.runtime.appid, function (widgetInfo) {
      if (platform !== 'ios') {
        if (uni.getStorageSync('username')) {
          uni.setStorageSync('version', widgetInfo.version)
          that.checkUpdate(widgetInfo.version)
        }
      }
    })
    // #endif
    // if (uni.getStorageSync('username')) {
    //   uni.setStorageSync('version', '1.0.4')
    //   that.checkUpdate('1.0.4')
    // }
  },
  onHide() {
    if (this.firsLogin === 'firsLogin') {
      uni.clearStorageSync()
    }
  },
  computed: {
    ...mapState({
      firsLogin: (state) => state.user.firsLogin
    })
  },
  methods: {
    // 接口
    getClock() {
      this.$u.api.getClock({ beginDate: this.beginDate, endDate: this.endDate }).then(res => {
        if (res.code === 200) {
          const pageItems = res.data.pageItems
          const holidayList = pageItems.filter((item) => {
            if (item.checked === 1) {
              item.checked = true
            } else {
              item.checked = false
            }
            return item.progress !== '04'
          })
          this.holidayList = holidayList
          this.clockList = holidayList.filter((item) => {
            return item.orderDate === this.fulldate
          })
          const length = this.clockList.filter((item) => {
            return item.checked === true
          })
          if (length.length === this.clockList.length) {
            this.checked = true
          } else {
            this.checked = false
          }
          // 同步日历
          const fullDate = holidayList.map(item => ({ date: item.orderDate, info: item.checked === true ? '已打卡' : '未打卡' }))
          // 使用reduce和对象来构建去重后的数组
          const uniqueData = Object.values(fullDate.reduce((acc, item) => {
            // 如果当前日期的info为"未打卡"，或者acc中还没有这个日期
            if (item.info === '未打卡' || !acc[item.date]) {
              // 更新或添加该日期的记录
              acc[item.date] = item
            }
            // 如果acc中已有该日期，但info不是"未打卡"，则不更新（因为已经是"未打卡"或更优先的记录了）
            return acc
          }, {}))
          this.info.selected = uniqueData
        }
      })
    },
    // 日历
    calendarChange(e) {
      this.fulldate = e.fulldate
      this.clockList = this.holidayList.filter((item) => {
        return item.orderDate === e.fulldate
      })
      setTimeout(() => {
        const name = this.clockList.filter(item => { return item.checked === true })
        if (name.length === this.clockList.length) {
          this.checked = true
        } else {
          this.checked = false
        }
      }, 300)
    },
    monthSwitch(e) {
      const [beginDate, endDate] = dateInterval(e.year, e.month)
      this.beginDate = beginDate
      this.endDate = endDate
      this.fulldate = beginDate
      this.getClock()
    },
    // 复选框
    checkedAll(e) {
      this.clockList.map(val => {
        val.checked = e.value
        val.done = e.value
      })
    },
    checkboxChange(e) {
      setTimeout(() => {
        const name = this.clockList.filter(item => { return item.checked === true })
        const text = this.clockList.filter(item => { return item.text === e.name })
        if (name.length === this.clockList.length) {
          this.checked = true
        } else {
          this.checked = false
        }
        this.clockList.forEach(item => {
          if (text[0].text === item.text) { item.done = e.value }
        })
      }, 300)
    },
    // 打卡
    clockOrder() {
      // 使用一个Set来存储已经遇到的cureOrderNO
      const map = {}
      this.clockList.forEach(item => {
        if (!map[item.cureOrderNO] || (map[item.cureOrderNO] && !map[item.cureOrderNO].curePhoto && item.curePhoto)) {
          map[item.cureOrderNO] = item
        }
      })
      // 从映射中提取唯一的对象数组
      const uniqueData = Object.values(map)
      const list = uniqueData.filter(item => item.facePhoto != null && item.facePhoto !== '')
      list.forEach((item) => {
        item.faceList = [{ url: `http://${uni.getStorageSync('baseURL')}${item.facePhoto}` }]
        if (item.curePhoto != null && item.curePhoto !== '') {
          item.fileList = [{ url: `http://${uni.getStorageSync('baseURL')}${item.curePhoto}` }]
        } else {
          item.fileList = []
        }
      })
      const lister = list.map(item => ({
        facePhoto: item.facePhoto, faceList: item.faceList, curePhoto: item.curePhoto, fileList: item.fileList, cureOrderNO: item.cureOrderNO
      }))
      uni.navigateTo({
        url: `/pages/home/clock?list=` + encodeURIComponent(JSON.stringify(lister)),
        animationType: 'slide-in-bottom',
        animationDuration: 100,
        events: {
          someEvent: (res) => {
            res.data.forEach(e => {
              this.clockList.forEach(item => {
                if (e.cureOrderNO === item.cureOrderNO) {
                  item.curePhoto = e.curePhoto
                }
              })
            })
            this.content = '任务已完成, 是否打卡?'
            this.deleteShow = true
          }
        }
      })
    },
    handleClock() {
      const clockOrderNOs = JSON.parse(JSON.stringify(this.clockList))
      clockOrderNOs.forEach(item => {
        if (item.checked === true) {
          item.checked = 1
        } else {
          item.checked = 0
        }
      })
      this.$u.api.getCalendarClock({ clockOrderNOs }).then(async(res) => {
        if (res.code === 200) {
          this.showToast('打卡成功！', 'success')
          await this.getClock()
          const name = this.clockList.filter(item => { return item.checked === true })
          if (name.length === this.clockList.length) {
            this.info.selected.push({
              date: this.fulldate,
              info: '已打卡'
            })
            this.info.selected.forEach(item => {
              if (item.date === this.fulldate) {
                item.info = '已打卡'
              }
            })
          } else {
            this.info.selected.push({
              date: this.fulldate,
              info: '未打卡'
            })
            this.info.selected.map(item => {
              if (item.date === this.fulldate) {
                item.info = '未打卡'
              }
            })
          }
        }
      })
    },
    showToast(e, type) {
      this.$refs.uToast.show({
        title: e,
        type: type
      })
    },
    // 版本升级
    async checkUpdate(version) {
      const res = await this.$u.api.getFileVersions({ version })
      if (res.code === 200) {
        const data = res.data.pageItems
        uni.setStorageSync('downUrl', data.pkgUrl)
        // data.versionOrderNO 有值则有新的更新包可用于更新
        if (data.versionOrderNO) {
          // data.updateWay == true 版本跨度过大，选择整包升级
          // data.updateWay == false 版本跨度为一个版本，执行补丁升级
          if (data.updateWay) {
            this.title = '*新版本升级'
            this.wgtUrl = `http://${uni.getStorageSync('baseURL')}${data.pkgUrl}`
          } else {
            this.title = '新版本升级'
            this.wgtUrl = `http://${uni.getStorageSync('baseURL')}${data.wgtUrl}`
          }
          // 升级信息
          this.msg = data.messageCheck
          // 全部用户提示升级
          this.show = true
        }
      }
    },
    confirm() {
      var that = this
      this.showProgress = true
      // 下载升级包
      uni
        .downloadFile({
          url: that.wgtUrl,
          success: (downloadResult) => {
            if (downloadResult.statusCode === 200) {
              // 下载完成后调用软件安装升级包
              // #ifdef APP-PLUS
              plus.runtime.install(
                downloadResult.tempFilePath,
                {
                  force: false
                },
                () => {
                  this.$refs.uToast.show({ title: '更新成功！', type: 'success' })
                  // 安装完成后软件重启,完成更新
                  plus.runtime.restart()
                },
                (err) => {
                  this.$refs.uToast.show(`安装失败: ${JSON.stringify(err)}`)
                }
              )
              // #endif
            }
          }
        })
        .onProgressUpdate((res) => {
          this.progress = res.progress
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
